//
//  ScrollLabelView.m
//  ScrollLabel
//
//  Created by zhao on 16/9/10.
//  Copyright © 2016年 zhao. All rights reserved.
//

#import "ScrollDetailLabelView.h"

static void each_object(NSArray *objects, void (^block)(id object))
{
    for(id obj in objects){
        block(obj);
    }
}
//宏定义 给Label的属性赋值
#define EACH_LABEL(ATTRIBUTE, VALUE) each_object(self.labels, ^(UILabel *label) {label.ATTRIBUTE = VALUE; })
#define HEIGHT self.frame.size.height

@interface ScrollDetailLabelView ()

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) NSMutableArray *labels;
@property (nonatomic, strong) UILabel *mainLabel; /**< 没滚动就能看到的Label*/


@end

@implementation ScrollDetailLabelView

- (instancetype)init
{
    if([super init])
    {
        [self initData];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if([super initWithFrame:frame])
    {
        [self initData];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if([super initWithCoder:aDecoder])
    {
        [self initData];
    }
    return self;
}

- (void)initData
{
    self.textFont = [UIFont systemFontOfSize:25];
    self.textColor = [UIColor whiteColor];
    
    self.velocity = 30.0;
    self.space = 25;
    self.pauseTimeIntervalBeforeScroll = 2;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    [self addSubview:self.scrollView];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark -- 滚动设置


- (void)setAttrText:(NSMutableAttributedString *)attrText{
    
    _attrText = attrText;
    EACH_LABEL(attributedText, attrText);
    EACH_LABEL(font, self.textFont);
    EACH_LABEL(textColor, self.textColor);
    [self refreshAttrLabelsFrame:attrText];
}

- (void)refreshAttrLabelsFrame:(NSMutableAttributedString *)attrText{
   
    if(attrText.length == 0) return;
    self.scrollView.cl_width = self.cl_width;
    CGSize labelSize = [attrText.string boundingRectWithSize:CGSizeMake(MAXFLOAT, HEIGHT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.textFont} context:nil].size;
    __block CGFloat offset = 0;
    if (labelSize.width <= self.cl_width) {
        self.scrollView.contentSize = self.bounds.size;
        [self.scrollView.layer removeAllAnimations];
        self.mainLabel.frame = CGRectMake(0, 0, self.cl_width, HEIGHT);
        self.mainLabel.attributedText = attrText;
        return;
    }
    each_object(self.labels, ^(UILabel *label) {
        label.attributedText = attrText;
        CGFloat labelWidth = (labelSize.width+10) > self.cl_width ? labelSize.width + self.space :self.cl_width;
        label.frame = CGRectMake(offset, 0, labelWidth, HEIGHT);
        offset += labelWidth;
    });
    
    self.scrollView.contentSize = CGSizeZero;
    [self.scrollView.layer removeAllAnimations];
    if(labelSize.width + 10 >  self.cl_width){
        self.scrollView.contentSize = CGSizeMake(self.cl_width + self.space + CGRectGetWidth(self.mainLabel.frame), HEIGHT);
        [self scrollLabelIfNeed];
    }else{
        EACH_LABEL(hidden, (self.mainLabel != label));
        self.scrollView.contentSize = self.bounds.size;
        [self.scrollView.layer removeAllAnimations];
    }
   
    
//    if(attrText.length == 0) return;
//    self.scrollView.cl_width = self.cl_width;
//
//    UILabel *tempLb = [[UILabel alloc]init];
//    tempLb.text = attrText.string;
//    [tempLb sizeToFit];
//    CGSize size = tempLb.frame.size;
//
//    __block CGFloat offset = 0;
//    if (size.width <= self.cl_width) {
//        self.scrollView.contentSize = self.bounds.size;
//        [self.scrollView.layer removeAllAnimations];
//        self.mainLabel.frame = CGRectMake(0, 0, self.cl_width, HEIGHT);
//        self.mainLabel.attributedText = attrText;
//        return;
//    }
//    each_object(self.labels, ^(UILabel *label) {
//
//        CGFloat labelWidth = (size.width+10) > self.cl_width ? size.width + self.space :self.cl_width;
//        label.frame = CGRectMake(offset, 0, labelWidth, HEIGHT);
//        offset += labelWidth;
//        label.attributedText = attrText;
//    });
//
//    self.scrollView.contentSize = CGSizeZero;
//    [self.scrollView.layer removeAllAnimations];
//    if(size.width + 10 >  self.cl_width){
//        self.scrollView.contentSize = CGSizeMake(self.cl_width + self.space + CGRectGetWidth(self.mainLabel.frame), HEIGHT);
//        [self scrollLabelIfNeed];
//    }else{
//        EACH_LABEL(hidden, (self.mainLabel != label));
//        self.scrollView.contentSize = self.bounds.size;
//        [self.scrollView.layer removeAllAnimations];
//    }
}

- (void)setText:(NSString *)theText
{
    if([self.text isEqualToString:theText]) return;
    
    _text = theText;
    EACH_LABEL(text, theText);
    EACH_LABEL(font, self.textFont);
    EACH_LABEL(textColor, self.textColor);
    
    [self refreshLabelsFrame:theText];
}

/**
 *  根据Label的内容更新Label的frame
 */
- (void)refreshLabelsFrame:(NSString *)labelText
{
    if(labelText.length == 0) return;
    self.scrollView.cl_width = self.cl_width;
    CGSize labelSize = [labelText boundingRectWithSize:CGSizeMake(MAXFLOAT, HEIGHT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.textFont} context:nil].size;
    __block CGFloat offset = 0;
    if (labelSize.width <= self.cl_width) {
        self.scrollView.contentSize = self.bounds.size;
        [self.scrollView.layer removeAllAnimations];
        self.mainLabel.frame = CGRectMake(0, 0, self.cl_width, HEIGHT);
        self.mainLabel.text = labelText;
        return;
    }
    each_object(self.labels, ^(UILabel *label) {
        CGFloat labelWidth = (labelSize.width+10) > self.cl_width ? labelSize.width + self.space :self.cl_width;
        label.frame = CGRectMake(offset, 0, labelWidth, HEIGHT);
        offset += labelWidth;
    });
    
    self.scrollView.contentSize = CGSizeZero;
    [self.scrollView.layer removeAllAnimations];
    if(labelSize.width + 10 >  self.cl_width){
        self.scrollView.contentSize = CGSizeMake(self.cl_width + self.space + CGRectGetWidth(self.mainLabel.frame), HEIGHT);
        [self scrollLabelIfNeed];
    }else{
        EACH_LABEL(hidden, (self.mainLabel != label));
        self.scrollView.contentSize = self.bounds.size;
        [self.scrollView.layer removeAllAnimations];
    }
}

/**
 *  循环滚动Label
 */
- (void)scrollLabelIfNeed
{
    NSTimeInterval duration = (CGRectGetWidth(self.mainLabel.frame) - self.cl_width)/self.velocity;
    [self.scrollView.layer removeAllAnimations];
    //重置contentOffset 否则不会循环滚动
    self.scrollView.contentOffset = CGPointZero;
    
    [UIView animateWithDuration:duration delay:self.pauseTimeIntervalBeforeScroll options:UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionCurveLinear animations:^{
        
        self.scrollView.contentOffset = CGPointMake(CGRectGetWidth(self.mainLabel.frame), 0);
    } completion:^(BOOL finished) {
        if(finished)
        {
            [self performSelector:@selector(scrollLabelIfNeed) withObject:nil];
        }
    }];
}

- (void)stopScrollView{

    self.scrollView.cl_width = self.cl_width;
    self.scrollView.contentSize = CGSizeZero;
    [self.scrollView.layer removeAllAnimations];

}
- (void)continueScrollView{
    self.scrollView.cl_width = self.cl_width;
    [self refreshLabelsFrame:self.text];
}

#pragma mark -- 进入后台 前台

- (void)addObaserverNotification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    //活跃状态
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(scrollLabelIfNeed) name:UIApplicationDidBecomeActiveNotification object:nil];
    //即将进入前台
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(scrollLabelIfNeed) name:UIApplicationWillEnterForegroundNotification object:nil];
}

#pragma mark --  getter

- (UIScrollView *)scrollView
{
    if(!_scrollView)
    {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.cl_width, HEIGHT)];
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        [self addSubview:_scrollView];
    }
    return _scrollView;
}

- (NSMutableArray *)labels
{
    if(!_labels)
    {
        _labels = [[NSMutableArray alloc] init];
        for(int i=0; i<2; i++)
        {
            UILabel *label = [[UILabel alloc] init];
            label.textAlignment = NSTextAlignmentLeft;
            label.backgroundColor = [UIColor clearColor];
            [self.labels addObject:label];
            [self.scrollView addSubview:label];
        }
    }
    return _labels;
}

- (UILabel *)mainLabel
{
    return self.labels[0];
}

- (CGSize)getStringRect:(NSAttributedString *)aString width:(CGFloat)width height:(CGFloat)height
{
    CGSize size = CGSizeZero;
    NSMutableAttributedString *atrString = [[NSMutableAttributedString alloc] initWithAttributedString:aString];
    NSRange range = NSMakeRange(0, atrString.length);
    
    //获取指定位置上的属性信息，并返回与指定位置属性相同并且连续的字符串的范围信息。
    NSDictionary* dic = [atrString attributesAtIndex:0 effectiveRange:&range];
    //不存在段落属性，则存入默认值
    NSMutableParagraphStyle *paragraphStyle = dic[NSParagraphStyleAttributeName];
    if (!paragraphStyle || nil == paragraphStyle) {
        paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
        paragraphStyle.lineSpacing = 0.0;//增加行高
        paragraphStyle.headIndent = 0;//头部缩进，相当于左padding
        paragraphStyle.tailIndent = 0;//相当于右padding
        paragraphStyle.lineHeightMultiple = 0;//行间距是多少倍
        paragraphStyle.alignment = NSTextAlignmentLeft;//对齐方式
        paragraphStyle.firstLineHeadIndent = 0;//首行头缩进
        paragraphStyle.paragraphSpacing = 0;//段落后面的间距
        paragraphStyle.paragraphSpacingBefore = 0;//段落之前的间距
        [atrString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];
    }
    
    //设置默认字体属性
    UIFont *font = dic[NSFontAttributeName];
    if (!font || nil == font) {
        font = [UIFont fontWithName:@"HelveticaNeue" size:12.0];
        [atrString addAttribute:NSFontAttributeName value:font range:range];
    }
    
    NSMutableDictionary *attDic = [NSMutableDictionary dictionaryWithDictionary:dic];
    [attDic setObject:font forKey:NSFontAttributeName];
    [attDic setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
    
    CGSize strSize = [[aString string] boundingRectWithSize:CGSizeMake(width, height)
                                                    options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                                 attributes:attDic
                                                    context:nil].size;
    
    size = CGSizeMake(strSize.width, strSize.height);
    return size;
}

@end
